package com.android.volley.toolbox;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;

public class RoundCornerDecorator implements BitmapDecorator {

	private static RoundCornerDecorator mDecorator;

	private RoundCornerDecorator() {

	}

	public synchronized static RoundCornerDecorator getInstance() {
		return mDecorator == null ? mDecorator = new RoundCornerDecorator() : mDecorator;
	}

	@Override
	public Bitmap decorate(Bitmap originalBitmap) {
		if (originalBitmap == null || originalBitmap.isRecycled()) {
			return null;
		}
		Bitmap output = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Config.ARGB_8888);
		try {
			Canvas canvas = new Canvas(output);

			final int color = 0xff424242;
			final Paint paint = new Paint();
			final Rect rect = new Rect(0, 0, originalBitmap.getWidth(), originalBitmap.getHeight());
			final RectF rectF = new RectF(rect);
			float roundPx = 10;
			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			paint.setColor(color);
			canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(originalBitmap, rect, rect, paint);
			originalBitmap.recycle();
			originalBitmap = null;
			return output;
		} catch (Throwable e) {
			e.printStackTrace();
			output.recycle();
			output = null;
			return originalBitmap;
		}

	}

}
